package com.zsj.mode.mvc;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;


class Model {
    private List<Observer> observers = new ArrayList<>();
    private String data;

    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    public String getData() {
        return data;
    }

    public void setData(String newData) {
        this.data = newData;
        notifyObservers();
    }

    private void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(data);
        }
    }
}
//观察者是视图
//被观察者是按钮
//一旦按钮发生了点击事件 就通知视图中的两个标签进行数据变化

class View extends JPanel implements Observer {
    private JLabel label;
    private JLabel label2;

    public View() {
        label = new JLabel("初始化1");
        label2 = new JLabel("初始化2");
        add(label);
        add(label2);
    }

    @Override
    public void update(String data) {
        label.setText("J1:更新数据: " + data);
        label2.setText("J2:我也得到了数据" + data);
    }
}


interface Observer {
    void update(String data);
}

class Controller implements ActionListener {
    private Model model;
    private View view;
    private int version = 1;

    public Controller(Model model, View view) {
        this.model = model;
        this.view = view;
        model.addObserver(view);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        model.setData("新数据" + version++ + "版本");
    }
}

/**
 * @Author zsj
 * @Version 1.0
 * @Date 2023/12/3 12:44
 * @Description
 */
public class MVCObservableExample {
    public static int count = 0;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            Model model = new Model();
            View view = new View();
            Controller controller = new Controller(model, view);
            // 添加一个简单的按钮，点击时改变模型的数据
            JButton add = new JButton("添加数据");
            JButton button = new JButton("改变数据");
            button.addActionListener(controller);
            JPanel panel = new JPanel();
            panel.add(button);
            panel.add(add);

            JFrame frame = new JFrame("带有观察者模式的MVC");
            frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
            frame.add(view);
            frame.add(panel);
            add.addActionListener(e -> {
                frame.add(new Panel().add(new Label("data"+count++)));
            });

            frame.setSize(400, 300);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);

        });
    }
}
